package com.ruoyi.common.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Component
public class WXUrlUtils implements Serializable {

    public static String APP_ID_WL = "wx2e64fffeccb44313";
    public static String APP_SECRET_WL = "8caef4b0b893d2bdc7d0e7ecb77049e9";

    public JSONObject getPhoneNumber(String code) {
        String token = getWLToken();
        //获取phone
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
                + "?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        HttpRequest request = HttpRequest.post(url);
        request.body(jsonObject.toString());
        HttpResponse response = request.execute();
        String body = response.body();
        JSONObject object = JSONObject.parseObject(body);
        return object.getJSONObject("phone_info");
    }

    public String getWLToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?";
        Map<String, Object> map = new HashMap<>();
        map.put("grant_type","client_credential");
        map.put("appid", APP_ID_WL);
        map.put("secret",APP_SECRET_WL);
        url += HttpUtil.toParams(map);
        HttpRequest request = HttpRequest.get(url);
        HttpResponse response = request.execute();
        String body = response.body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        String token = jsonObject.getString("access_token");
        return token;
    }
}
